package com.teacher.hong.servlet.clazz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.teacher.hong.entity.Clazz;
import com.teacher.hong.service.IClazzService;
import com.teacher.hong.service.impl.ClazzServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 新增/修改班级
 */
//@WebServlet("/clazz/edit")
public class ClazzEditServlet extends HttpServlet {

    IClazzService clazzService;

    @Override
    public void init() throws ServletException {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        clazzService = context.getBean("clazzService", ClazzServiceImpl.class);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        Integer clazzId = req.getParameter("clazzId") == null ? null : Integer.parseInt(req.getParameter("clazzId"));
        String clazzName = req.getParameter("clazzName");

        Clazz clazz = new Clazz(clazzId, clazzName);
        boolean success = clazzService.save(clazz);


        JSONObject object = new JSONObject(true);
        object.put("state", success ? 200 : 402);
        object.put("message", success ? "success" : "fail, clazzName is exists.");
        object.put("timestamp", LocalDateTime.now());

        resp.setStatus(success ? 200 : 402);

        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(object.toJSONString());

    }
}
